package shuzi.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.drawable.Drawable;


public class Download {
	
	public static Drawable byteToDrawable(byte[] byteArray) {
		ByteArrayInputStream ins = new ByteArrayInputStream(byteArray);
		return Drawable.createFromStream(ins, null);
	}
	
	
	/**
	 * 从网络上读取图片
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static byte[] getImage(String path) throws Exception {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			InputStream inStream = conn.getInputStream();//ͨ����������ȡͼƬ���
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024*6];
			int len = 0;
			while( (len=inStream.read(buffer)) != -1 ){
				outStream.write(buffer, 0, len);
			}
			inStream.close();
			return outStream.toByteArray();
		}
	
/*	public static byte[] ReadText(Context context,String fileName,String path) throws Exception{
		FileInputStream in = null;
		ByteArrayOutputStream out = null;
		File file = new File(Database.dir, fileName);
		try {
			in = new FileInputStream(file);
			out = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024*6];
			int len = 0;
			try {
				while( (len=in.read(buffer)) != -1 ){
					out.write(buffer, 0, len);
				}
			} catch (IOException e) {
			
				e.printStackTrace();
			}
			   in.close();
		} catch (FileNotFoundException e) {
			//downWrite(path,context,fileName);
		
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		///System.out.println("�����չ�");
		return out.toByteArray();
	}
	
	 public static void WriteText(Context context, String fileName,byte[] data)
	 {
		 File file = new File(Database.dir, fileName);
		 
	       FileOutputStream fOut = null;
	       try{
	    	   //file.createNewFile();
	           fOut =new FileOutputStream(file);
	           fOut.write(data);
	           fOut.flush();
	           //System.out.println("save");
	           }
	           catch (Exception e) 
	           {      
	           e.printStackTrace();
	           }
	           finally 
	           {
	              try {
	                     fOut.close();
	                   } 
	              catch (IOException e)
	               {
	                    e.printStackTrace();
	                 }
	           }
	  }
	public static byte[] downWrite(String path,Context context, String fileName) throws Exception{
		
		WriteText(context,fileName,getImage(path));
		System.out.println("finish");
		
		return getImage(path);
	}*/

}



